package edu.itla.medifacil.controllers;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import edu.itla.medifacil.helpers.Utilities;
import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.entities.Speciality;
import edu.itla.medifacil.persistence.enums.Attribute;
import edu.itla.medifacil.persistence.managers.DoctorManager;
import edu.itla.medifacil.persistence.managers.SpecialityManager;

/**
 * Servlet implementation class Doctors
 */
public class Doctors extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final DoctorManager doctorManager;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Doctors() {
        super();
        this.doctorManager = new DoctorManager();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession(true).removeAttribute("doctor");
		request.getSession().removeAttribute("doctorAttributes");
		
		List<Speciality> specialities = new SpecialityManager().findAll();
		request.getSession(true).setAttribute("specialities", specialities);
		

		
		if( "add".equals(request.getParameter("action") ) ){
			response.sendRedirect("doctors/add.jsp");
		}else if( request.getParameter("id") != null){
			int doctorId = Integer.parseInt(request.getParameter("id").toString());
			
			People doctor = doctorManager.find(doctorId);
			prepareDoctorInfo(doctor, request);
			
			if( request.getParameter("action").equals("view"))
				response.sendRedirect("doctors/view.jsp");
			else if( request.getParameter("action").equals("edit") )
				response.sendRedirect("doctors/edit.jsp");
			else if( request.getParameter("action").equals("delete") )
				doctorManager.delete( Integer.parseInt(request.getParameter("id").toString()) );
		}else{
			List<People> doctors = doctorManager.findAll();
			request.getSession(true).removeAttribute("doctors");
			request.getSession().setAttribute("doctors", doctors);
			response.sendRedirect("doctors/");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("rawtypes")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> parameters = new HashMap<String, String>();
		String cwd = request.getSession().getServletContext().getRealPath("/");
		
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		
		if( ServletFileUpload.isMultipartContent(request) ){
			try {
				List items = uploadHandler.parseRequest(request);
				Iterator itr = items.iterator();
				while(itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					parameters.put( "attributes." + Attribute.FOTO.getId(), "/img/doctors/" + parameters.get("identification") + ".jpg");
					if(! item.isFormField() && item.getName().length() > 0 ) {
						File file = new File( cwd + "img/doctors/", parameters.get("identification") + ".jpg");
						item.write(file);
					}else{
						parameters.put(item.getFieldName(), item.getString());
					}
				}
			}catch(Exception ex) {
				log("Error encountered while parsing the request",ex);
			}
		}
		
		People doctor = doctorManager.save(parameters);
		prepareDoctorInfo(doctor, request);
		response.sendRedirect("doctors/view.jsp");
		
	}
	
	private void prepareDoctorInfo( People doctor, HttpServletRequest request){
		Map<Integer, String> doctorAttributes = Utilities.extractPersonAttributes(doctor);
		
		request.getSession(true).setAttribute("doctor", doctor);
		request.getSession().setAttribute("doctorAttributes", doctorAttributes);
	}

}
